﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CrmContacto.Contracts.Contracts;
using Web.CrmContacto.Code;
using Web.Framework;
using Web.Framework.Translate;
using CrmContacto.Contracts.Contracts.Search;
using CrmContacto.WebApp.Code.InnerClasses;
using CrmContacto.Contracts.Enums;
using System.Text;
using CrmContacto.Contracts;
using Web.CrmContacto.Code.Security;
using Web.Framework.Helpers;

namespace CrmContacto.WebApp.App
{
    public partial class AccionDeMarketingPromocionEdit : BasePage
    {
        public AccionDeMarketingPromocion accionDeMarketingCurrent
        {
            get
            {
                return (AccionDeMarketingPromocion)ViewState["accionDeMarketingCurrent"];
            }
            set
            {
                ViewState["accionDeMarketingCurrent"] = value;
            }
        }

        public PlanDeMarketing planDeMarketingCurrent
        {
            get
            {
                return (PlanDeMarketing)ViewState["planDeMarketingCurrent"];
            }
            set
            {
                ViewState["planDeMarketingCurrent"] = value;
            }
        }

        //public string disabledTabs
        //{
        //    get
        //    {
        //        string disabledTabsStr = string.Empty;
        //        if (accionDeMarketingCurrent != null && accionDeMarketingCurrent.Id == 0)
        //        {
        //            disabledTabsStr = "[1,2,3,4]";
        //        }
        //        else
        //        {
        //            disabledTabsStr = "[]";
        //        }
        //        return disabledTabsStr;
        //    }
        //}

        private List<LinkButton> actionButtons = new List<LinkButton>();

        //LinkButton agregarListaButton = new LinkButton();
        //LinkButton agregarResultadosButton = new LinkButton();
        LinkButton agregarAmbitosButton = new LinkButton();
        LinkButton agregarComunicacionesButton = new LinkButton();
        LinkButton btnCancelarPlanButton = new LinkButton();
        LinkButton btnFinalizarPlanButton = new LinkButton();
        LinkButton eliminarButton = new LinkButton();
        LinkButton guardarButton = new LinkButton();
        LinkButton volverAPlanButton = new LinkButton();

        protected override void ApplySecurity()
        {
            base.ApplySecurity();

            if (this.accionDeMarketingCurrent != null)
            {
                this.volverAPlanButton.Visible =
                this.lnkIrAPlan.Visible = HasPermissionFor(CrmSecurity.MARKETINGPLAN_SEARCH);

                this.lnkReglaIrA.Visible = HasPermissionFor(CrmSecurity.MANAGE_PROMO_RULES);

                if (this.accionDeMarketingCurrent.Id != 0)
                {
                    HasPermissionToSeeMe(CrmSecurity.MARKETINGACTION_SEARCH, CrmSecurity.MARKETINGACTION_EDIT, CrmSecurity.MARKETINGACTION_SEARCH);

                    agregarAmbitosButton.Visible = HasPermissionFor(CrmSecurity.MARKETINGACTION_ADD_PDV);
                    agregarComunicacionesButton.Visible = HasPermissionFor(CrmSecurity.MARKETINGACTION_ADD_ACTION);
                    btnFinalizarPlanButton.Visible = HasPermissionFor(CrmSecurity.MARKETINGACTION_CHANGE_STATE);
                    eliminarButton.Visible = HasPermissionFor(CrmSecurity.MARKETINGACTION_DELETE);
                    guardarButton.Visible =
                    lnkGuardar.Visible = HasPermissionFor(CrmSecurity.MARKETINGACTION_EDIT);

                    if ((EstadoPlanDeMarketing)accionDeMarketingCurrent.Estado == EstadoPlanDeMarketing.Finalizado ||
                        (EstadoPlanDeMarketing)accionDeMarketingCurrent.Estado == EstadoPlanDeMarketing.Cancelado)
                    {
                        this.btnCancelarPlanButton.Visible = false;
                        this.btnFinalizarPlanButton.Visible = false;
                        this.agregarAmbitosButton.Visible = false;
                        this.agregarComunicacionesButton.Visible = false;
                    }

                    SetJavascriptForDeleteRecord(eliminarButton, accionDeMarketingCurrent.Nombre);

                    // Grillas    
                    if (GridListasDistribucion.DataSource != null)
                    {
                        GridListasDistribucion.Columns[0].Visible = HasPermissionFor(CrmSecurity.MARKETINGACTION_ADD_DISTRIBUTIONLIST);
                        GridListasDistribucion.Columns[1].Visible = HasPermissionFor(CrmSecurity.MARKETINGACTION_REMOVE_DISTRIBUTIONLIST);
                    }

                    if (GridAccionesDeMarketing.DataSource != null)
                    {
                        GridAccionesDeMarketing.Columns[0].Visible = HasPermissionFor(CrmSecurity.MARKETINGACTION_ADD_ACTION);
                        GridAccionesDeMarketing.Columns[1].Visible = HasPermissionFor(CrmSecurity.MARKETINGACTION_REMOVE_ACTION);
                    }

                    if (GridAmbito.DataSource != null)
                    {
                        GridAmbito.Columns[0].Visible = HasPermissionFor(CrmSecurity.MARKETINGACTION_ADD_PDV);
                        GridAmbito.Columns[1].Visible = HasPermissionFor(CrmSecurity.MARKETINGACTION_REMOVE_PDV);
                    }

                    if (GridResultados.DataSource != null)
                    {
                        GridResultados.Columns[0].Visible = HasPermissionFor(CrmSecurity.MARKETINGACTION_ADD_EMAILRESULTS);
                        GridResultados.Columns[1].Visible = HasPermissionFor(CrmSecurity.MARKETINGACTION_REMOVE_EMAILRESULTS);
                    }
                }
                else
                {
                    HasPermissionToSeeMe(CrmSecurity.MARKETINGACTION_CREATE);
                    agregarAmbitosButton.Visible = false;
                    agregarComunicacionesButton.Visible = false;
                    btnCancelarPlanButton.Visible = false;
                    btnFinalizarPlanButton.Visible = false;
                    eliminarButton.Visible = false;
                    guardarButton.Visible =
                    lnkGuardar.Visible = HasPermissionFor(CrmSecurity.MARKETINGACTION_CREATE);
                }
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
           
            guardarButton.ID = "BoCommandGuardar";
            guardarButton.Text = LocalizationProvider.Instance["Bo.Command.Guardar"];
            guardarButton.Click += new EventHandler(lnkSaveButton_Click);
            guardarButton.OnClientClick = "return window.AccionDeMarketingEditObj.ValidateGuardar();";
            actionButtons.Add(guardarButton);

            lnkGuardar.Click += new EventHandler(lnkSaveButton_Click);
            lnkGuardar.OnClientClick = "return window.AccionDeMarketingEditObj.ValidateGuardar();";
            
            volverAPlanButton.ID = "BoCommandVolver";
            volverAPlanButton.CausesValidation = false;
            SetJavascriptForClientClickDirtyChech(volverAPlanButton);
            volverAPlanButton.Text = LocalizationProvider.Instance["Bo.AccionDeMarketing.ActionMenu.IrAPlan"];
            volverAPlanButton.Click += new EventHandler(volverButton_Click);
            actionButtons.Add(volverAPlanButton);

            //// Listas de distribucion            
            //agregarListaButton.ID = "BoAccionDeMarketingActionMenuAsociarListas";
            //agregarListaButton.Text = LocalizationProvider.Instance["Bo.AccionDeMarketing.ActionMenu.AsociarListas"];
            //agregarListaButton.Click += new EventHandler(agregarListaDistribucionButton_Click);
            //actionButtons.Add(agregarListaButton);

            //// Resultados            
            //agregarResultadosButton.ID = "BoAccionDeMarketingActionMenuAsociarResultados";
            //agregarResultadosButton.Text = LocalizationProvider.Instance["Bo.AccionDeMarketing.ActionMenu.AsociarResultados"];
            //agregarResultadosButton.Click += new EventHandler(agregarResultadosButton_Click);
            //actionButtons.Add(agregarResultadosButton);

            // Ambito            
            agregarAmbitosButton.ID = "BoAccionDeMarketingActionMenuAsociarAmbitos";
            agregarAmbitosButton.Text = LocalizationProvider.Instance["Bo.AccionDeMarketing.ActionMenu.AsociarAmbitos"];
            agregarAmbitosButton.Click += new EventHandler(agregarPuntoDeVentaButton_Click);
            SetJavascriptForClientClickDirtyChech(agregarAmbitosButton);
            agregarAmbitosButton.CausesValidation = false;
            actionButtons.Add(agregarAmbitosButton);

            // Comunicaciones Asociadas           
            agregarComunicacionesButton.ID = "BoAccionDeMarketingActionMenuAsociarComunicaciones";
            agregarComunicacionesButton.Text = LocalizationProvider.Instance["Bo.AccionDeMarketing.ActionMenu.AsociarComunicaciones"];
            agregarComunicacionesButton.Click += new EventHandler(agregarAccionRelacionadaButton_Click);
            SetJavascriptForClientClickDirtyChech(agregarComunicacionesButton);
            agregarComunicacionesButton.CausesValidation = false;
            actionButtons.Add(agregarComunicacionesButton);
            
            btnCancelarPlanButton.ID = "BoCommandCancelar";
            SetJavascriptForClientClickDirtyChech(btnCancelarPlanButton);
            btnCancelarPlanButton.Click += new EventHandler(CancelarButton_Click);
            btnCancelarPlanButton.Text = LocalizationProvider.Instance["Bo.Command.CambiarEstado.Cancelado"];
            SetJavascriptForClientClickDirtyChech(btnCancelarPlanButton);
            btnCancelarPlanButton.CausesValidation = false;
            actionButtons.Add(btnCancelarPlanButton);
            
            btnFinalizarPlanButton.ID = "BoCommandFinalizar";
            SetJavascriptForClientClickDirtyChech(btnFinalizarPlanButton);
            btnFinalizarPlanButton.Click += new EventHandler(FinalizarButton_Click);
            btnFinalizarPlanButton.Text = LocalizationProvider.Instance["Bo.Command.CambiarEstado.Finalizado"];
            SetJavascriptForClientClickDirtyChech(btnFinalizarPlanButton);
            btnFinalizarPlanButton.CausesValidation = false;
            actionButtons.Add(btnFinalizarPlanButton);
            
            eliminarButton.ID = "BoCommandEliminar";
            eliminarButton.CausesValidation = false;
            eliminarButton.Text = LocalizationProvider.Instance["Bo.Command.Eliminar"];
            eliminarButton.Click += new EventHandler(eliminarButton_Click);
            actionButtons.Add(eliminarButton);

            base.LoadContextActions(actionButtons);

            this.lnkIrAPlan.Click += new EventHandler(lnkIrAPlan_Click);
            this.lnkReglaIrA.Click += new EventHandler(lnkReglaIrA_Click);
        }

        private void eliminarButton_Click(object sender, EventArgs e)
        {
            try
            {
                WebServiceHelper.EliminarAccionDeMarketing(accionDeMarketingCurrent.Id);
                Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlPlanDeMarketingEdit + string.Format("?Id={0}&{1}=1", planDeMarketingCurrent.Id, MiscClass.QueryShowDeleted), true);
                //AccionDeMarketingPromocion accionDeMarketing = new AccionDeMarketingPromocion();
                //accionDeMarketing.PlanDeMarketingId = accionDeMarketingCurrent.PlanDeMarketingId;
                //accionDeMarketing.Discriminador = accionDeMarketingCurrent.Discriminador;
                //accionDeMarketing.PlanDeMarketingId = accionDeMarketingCurrent.PlanDeMarketingId;
                //accionDeMarketingCurrent = accionDeMarketing;
                //Bind();
                //this.masterPage.ShowMessage(LocalizationProvider.Instance["Bo.Message.RegistroEliminado"], WebMessageType.Notification);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void CancelarButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (accionDeMarketingCurrent.Id != 0)
                {
                    WebServiceHelper.CambiarEstadoAAccionDeMarketing(accionDeMarketingCurrent.Id, (int)EstadoPlanDeMarketing.Cancelado);
                    accionDeMarketingCurrent.Estado = (int)EstadoPlanDeMarketing.Cancelado;
                    Bind();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void FinalizarButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (accionDeMarketingCurrent.Id != 0)
                {
                    WebServiceHelper.CambiarEstadoAAccionDeMarketing(accionDeMarketingCurrent.Id, (int)EstadoPlanDeMarketing.Finalizado);
                    accionDeMarketingCurrent.Estado = (int)EstadoPlanDeMarketing.Finalizado;
                    Bind();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        //private void ActivarInactivarButton_Click(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        if (planDeMarketingCurrent.Id != 0 && planDeMarketingCurrent.Estado.HasValue)
        //        {
        //            EstadoCampania estado = (EstadoCampania)planDeMarketingCurrent.Estado;
        //            planDeMarketingCurrent.Estado = (int)(estado == EstadoCampania.Activa ? EstadoCampania.Inactiva : EstadoCampania.Activa);
        //            WebServiceHelper.ActivarEntidad(planDeMarketingCurrent.GetType().Name, planDeMarketingCurrent.Estado, planDeMarketingCurrent.Id);
        //            Bind();
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        ExceptionManager.Instance.HandleException(ex);
        //    }
        //}

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!this.IsPostBack)
                {
                    var crmService = ServiceFactory.ServiceFactory.Instance.GetCrmContactoAdminService();

                    if (this.Request.QueryString["Id"] == null)
                    {
                        int planDeMarketingId = Convert.ToInt32(this.Request.QueryString["PlanDeMarketingId"]);
                        int discriminadorId = Convert.ToInt32(this.Request.QueryString["DiscriminadorId"]);                        

                        accionDeMarketingCurrent = new AccionDeMarketingPromocion();
                        accionDeMarketingCurrent.PlanDeMarketingId = planDeMarketingId;
                        accionDeMarketingCurrent.Discriminador = discriminadorId; // Tienen que tener un tipo si o si                        
                        
                        // Cargo el plan de marketing
                        PlanDeMarketingSearch search = new PlanDeMarketingSearch()
                        {
                            Id = planDeMarketingId,
                            LoadAccionesDeMarketing = false,
                            EmpresaId = BasePage.CompanyId
                        };

                        planDeMarketingCurrent = WebServiceHelper.GetPlanesDeMarketing(search).First();
                    }
                    else
                    {
                        // Primero obtengo la configuracion
                        int AccionMarketingId = Convert.ToInt32(this.Request.QueryString["Id"]);                        

                        AccionDeMarketingSearch search = new AccionDeMarketingSearch()
                        {
                            Id = AccionMarketingId
                        };

                        search.LoadResultados = false;
                        search.LoadAmbitos = true;
                        search.LoadAccionesDeMarketingRelacionadas = true;
                        search.LoadListasDeDistribucion = false;

                        accionDeMarketingCurrent = crmService.GetAccionesDeMarketingPromocion(search).First();

                        PlanDeMarketingSearch searchPlan = new PlanDeMarketingSearch()
                        {
                            Id = accionDeMarketingCurrent.PlanDeMarketingId,
                            LoadAccionesDeMarketing = false,
                            EmpresaId = BasePage.CompanyId
                        };

                        planDeMarketingCurrent = WebServiceHelper.GetPlanesDeMarketing(searchPlan).First();
                    }

                    ////addingPuntosDeVentaOk
                    //if (this.Request.QueryString["addingListaDistribucionOk"] != null)
                    //{
                    //    this.masterPage.ShowMessage(LocalizationProvider.Instance["Bo.Messages.ListasAgregadasAAccionDeMarketing"], WebMessageType.Notification);
                    //    base.NavigationContext.AccionDeMarketingId = null;
                    //    base.NavigationContext.AgregandoListasDeDistribucionAAccionDeMarketing = false;
                    //}

                    //addingPuntosDeVentaOk
                    if (this.Request.QueryString["addingPuntosDeVentaOk"] != null)
                    {
                        this.masterPage.ShowMessage(LocalizationProvider.Instance["Bo.Messages.PuntosDeVentaAgregadosAAccionDeMarketing"], WebMessageType.Notification);
                        base.NavigationContext.AccionDeMarketingId = null;
                        base.NavigationContext.AgregandoPuntosDeVentaAAccionDeMarketing = false;
                    }

                    //addingAccionRelacionadaOk
                    if (this.Request.QueryString["addingAccionRelacionadaOk"] != null)
                    {
                        this.masterPage.ShowMessage(LocalizationProvider.Instance["Bo.Messages.AccionesDeMktgAgregadosAAccionDeMarketing"], WebMessageType.Notification);
                        base.NavigationContext.AccionDeMarketingId = null;
                        base.NavigationContext.AgregandoAccionesDeMarketingAAccionDeMarketing = false;
                    }

                    LoadCbos();

                    Bind();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void LoadCbos()
        {
            UIHelper.LoadEstados<AccionMarketingLlegadaEnum>(this.cboLlegada);

            var reglaList = WebServiceHelper.GetReglasAccionDeMarketing(new MaestroBaseSearch() { EmpresaId = BasePage.CompanyId});
            UIHelper.LoadCbo(reglaList, this.cboRegla, string.Empty);
        }

        private void Bind()
        {
            if (accionDeMarketingCurrent.Id == 0)
            {
                pnlTabs.Visible = false;
                this.agregarAmbitosButton.Visible = false;
                this.agregarComunicacionesButton.Visible = false;
                this.btnCancelarPlanButton.Visible = false;
                this.btnFinalizarPlanButton.Visible = false;
            }
            else
            {
                pnlTabs.Visible = true;
                this.agregarAmbitosButton.Visible = true;
                this.agregarComunicacionesButton.Visible = true;
                this.btnCancelarPlanButton.Visible = 
                this.btnFinalizarPlanButton.Visible = true;
            }

            DiscriminadorAccionDeMarketing discriminadorMarketing = (DiscriminadorAccionDeMarketing)this.accionDeMarketingCurrent.Discriminador;
            lblEspecificacionDeMarketing.Text = UIHelper.GetEnumDescription(discriminadorMarketing);
            this.txtNombrePlanDeMarketing.Text = this.planDeMarketingCurrent.Nombre;
            this.txtNombre.Text = this.accionDeMarketingCurrent.Nombre;
            this.txtDescripcion.Text = this.accionDeMarketingCurrent.Descripcion;
            this.txtResposable.Text = this.accionDeMarketingCurrent.Responsable;
            this.txtCodigo.Text = this.accionDeMarketingCurrent.CodigoParaPDV;
            this.lblEstado.Text = UIHelper.GetEnumDescription((EstadoPlanDeMarketing)accionDeMarketingCurrent.Estado);            

            // Estado
            if(this.accionDeMarketingCurrent.LlegadaId.HasValue)
            {
                this.cboLlegada.SelectedValue = this.accionDeMarketingCurrent.LlegadaId.Value.ToString();
            }

            if(this.accionDeMarketingCurrent.ReglaId.HasValue)
            {
                this.cboRegla.SelectedValue = this.accionDeMarketingCurrent.ReglaId.Value.ToString();
            }

            this.txtInversion.Text = UIHelper.GetStrFromDecimalMoney(this.accionDeMarketingCurrent.Inversion);
            this.txtROIDinero.Text = UIHelper.GetStrFromDecimalMoney(this.accionDeMarketingCurrent.ROIDinero);
            this.txtROIPorcentaje.Text = UIHelper.GetStrFromDecimalMoney(this.accionDeMarketingCurrent.ROIPorcentaje);
            this.txtEficaciaEsperada.Text = UIHelper.GetStrFromDecimalMoney(this.accionDeMarketingCurrent.EficaciaEsperada);

            UIHelper.BindDateTime(this.txtFechaDesde, this.accionDeMarketingCurrent.FechaDesde);
            UIHelper.BindDateTime(this.txtFechaHasta, this.accionDeMarketingCurrent.FechaHasta);

            BindGridListasDeDistribucion();
            BindGridResultados();
            BindAmbitos();
            BindComunicaciones();

            StringBuilder buildTabsMenu = new StringBuilder();

            buildTabsMenu.Append("<ul>");

            string strListaDistribucion = string.Format("<li><a href='#pnlListasDeDistribucion'>{0}</a></li>", LocalizationProvider.Instance["Bo.AccionDeMarketing.Tab.Listas"]);
            string strResultados = string.Format("<li><a href='#pnlResults'>{0}</a></li>", LocalizationProvider.Instance["Bo.AccionDeMarketing.Tab.Resultados"]);
            string strAmbito = string.Format("<li><a href='#pnlAmbito'>{0}</a></li>", LocalizationProvider.Instance["Bo.AccionDeMarketing.Tab.Ambitos"]);
            string strComunicaciones = string.Format("<li><a href='#pnlAccionesDeMarketing'>{0}</a></li>", LocalizationProvider.Instance["Bo.AccionDeMarketing.Tab.Comunicaciones"]);
            //<li ><a href="#pnlListasDeDistribucion">
            //<asp:Literal ID="Literal2" runat="server" Text='<%$ Code: LocalizationProvider.Instance["Bo.AccionDeMarketing.Tab.Listas"]%>' />
            //</a></li>

            switch (discriminadorMarketing)
            {
                case DiscriminadorAccionDeMarketing.Comunicacion:
                    ////divFechaEventoHasta.Visible = false;
                    ////litFechaEventoDesde.Text = LocalizationProvider.Instance["AccionDeMarketing.FechaEventoSoloDesde"];
                    //this.pnlAccionesDeMarketing.CssClass = "displayNone";
                    //this.agregarComunicacionesButton.Visible = accionDeMarketingCurrent.TipoComunicacion.Configuracion.IncluyeAccionesRelacionadas;
                    //this.agregarAmbitosButton.Visible = accionDeMarketingCurrent.TipoComunicacion.Configuracion.IncluyeSucursales;
                    //this.agregarListaButton.Visible = accionDeMarketingCurrent.TipoComunicacion.Configuracion.IncluyeListaDeDistribucion;
                    //this.agregarResultadosButton.Visible = accionDeMarketingCurrent.TipoComunicacion.Configuracion.IncluyeResultadoEmail;

                    //if (accionDeMarketingCurrent.TipoComunicacion.Configuracion.IncluyeListaDeDistribucion)
                    //    buildTabsMenu.Append(strListaDistribucion);

                    //if (accionDeMarketingCurrent.TipoComunicacion.Configuracion.IncluyeResultadoEmail)
                    //    buildTabsMenu.Append(strResultados);

                    //if (accionDeMarketingCurrent.TipoComunicacion.Configuracion.IncluyeSucursales)
                    //    buildTabsMenu.Append(strAmbito);

                    //if (accionDeMarketingCurrent.TipoComunicacion.Configuracion.IncluyeAccionesRelacionadas)
                    //    buildTabsMenu.Append(strComunicaciones);
                    //break;

                //case DiscriminadorAccionDeMarketing.Publicidad:
                //    this.pnlAccionesDeMarketing.CssClass = "displayNone";
                //    this.pnlAmbito.CssClass = "displayNone";
                //    this.pnlListasDeDistribucion.CssClass = "displayNone";
                //    this.pnlResults.CssClass = "displayNone";
                //    this.agregarComunicacionesButton.Visible = this.agregarAmbitosButton.Visible =
                //    this.agregarListaButton.Visible = this.agregarResultadosButton.Visible = false;
                //    pnlTabs.Visible = false;
                //    break;

                case DiscriminadorAccionDeMarketing.Promocion:                                       
                    this.pnlResults.CssClass = "displayNone";
                    this.pnlListasDeDistribucion.CssClass = "displayNone";
                    
                    //buildTabsMenu.Append(strListaDistribucion);
                    //buildTabsMenu.Append(strResultados);
                    buildTabsMenu.Append(strAmbito);
                    buildTabsMenu.Append(strComunicaciones);
                    break;
            }

            buildTabsMenu.Append("</ul>");

            litTabs.Text = buildTabsMenu.ToString();
        }

        private void BindGridListasDeDistribucion()
        {
            //this.GridListasDistribucion.DataSource = this.accionDeMarketingCurrent.ListaDeDistribucionList;
            //this.GridListasDistribucion.DataBind();
        }

        private void BindGridResultados()
        {
            //this.GridResultados.DataSource = this.accionDeMarketingCurrent.Resultados;
            //this.GridResultados.DataBind();
        }

        private void BindAmbitos()
        {
            this.GridAmbito.DataSource = this.accionDeMarketingCurrent.AmbitoList;
            this.GridAmbito.DataBind();
        }

        private void BindComunicaciones()
        {
            this.GridAccionesDeMarketing.DataSource = this.accionDeMarketingCurrent.AccionesDeMarketingRelacionadasList;
            this.GridAccionesDeMarketing.DataBind();
        }

        private void SetData()
        {
            this.accionDeMarketingCurrent.Nombre = this.txtNombre.Text;
            this.accionDeMarketingCurrent.Descripcion = this.txtDescripcion.Text;
            this.accionDeMarketingCurrent.CodigoParaPDV = this.txtCodigo.Text;
            this.accionDeMarketingCurrent.Responsable = this.txtResposable.Text;

            this.accionDeMarketingCurrent.FechaDesde = UIHelper.GetDateTimeFromInputText(this.txtFechaDesde.Text);
            this.accionDeMarketingCurrent.FechaHasta = UIHelper.GetDateTimeFromInputText(this.txtFechaHasta.Text);

            this.accionDeMarketingCurrent.Inversion = UIHelper.GetDecimalMoneyFromText(this.txtInversion.Text);
            this.accionDeMarketingCurrent.ROIDinero = UIHelper.GetDecimalMoneyFromText(this.txtROIDinero.Text);
            this.accionDeMarketingCurrent.ROIPorcentaje = UIHelper.GetDecimalMoneyFromText(this.txtROIPorcentaje.Text);
            this.accionDeMarketingCurrent.EficaciaEsperada = UIHelper.GetDecimalMoneyFromText(this.txtEficaciaEsperada.Text);
        }

        private void Save()
        {
            accionDeMarketingCurrent = WebServiceHelper.SaveAccionDeMarketingPromocion(accionDeMarketingCurrent);
            Bind();
        }

        protected void GridListasDistribucion_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "editar")
                {
                    int listaDistribucionId = Convert.ToInt32(this.GridListasDistribucion.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    this.Response.Redirect(string.Format(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlListaDeDistribucionEdit + "?Id={0}", listaDistribucionId), true);
                }
                else if (e.CommandName == "eliminar")
                {
                    int listaDistribucionId = Convert.ToInt32(this.GridListasDistribucion.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    WebServiceHelper.EliminarListaDistribucionDeAccionDeMarketing(accionDeMarketingCurrent.Id, listaDistribucionId);
                    var camp = accionDeMarketingCurrent.ListaDeDistribucionList.Where(i => i.Id == listaDistribucionId).Single();
                    accionDeMarketingCurrent.ListaDeDistribucionList.Remove(camp);
                    Bind();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridListasDistribucion_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    ListaDeDistribucion listaDeDistribucion = (ListaDeDistribucion)e.Row.DataItem;

                    e.Row.Cells[0].Attributes.Add("title", "Editar");
                    e.Row.Cells[1].Attributes.Add("title", "Eliminar");

                    ImageButton btnEditarCtrl = (ImageButton)e.Row.FindControl("btnEditar");
                    SetJavascriptForClientClickDirtyChech(btnEditarCtrl);

                    ImageButton btnEliminarCtrl = (ImageButton)e.Row.FindControl("btnEliminar");
                    SetJavascriptForDeleteRecord(btnEliminarCtrl, listaDeDistribucion.Nombre);                    
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private int colTipoRebote = 2;
        protected void GridResultados_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    AccionDeMarketingEmailResultado resultado = (AccionDeMarketingEmailResultado)e.Row.DataItem;

                    var cellRebote = e.Row.Cells[colTipoRebote];

                    if (!resultado.EmailTipoRebote.HasValue)
                    {
                        cellRebote.Text = string.Empty;
                    }
                    else
                    {
                        cellRebote.Text = resultado.EmailTipoRebote.Value ? LocalizationProvider.Instance["EstadoEmail.ReboteHard"] : LocalizationProvider.Instance["EstadoEmail.ReboteSoft"];
                    }

                    e.Row.Cells[0].Attributes.Add("title", "Eliminar");
                    ImageButton btnEliminarCtrl = (ImageButton)e.Row.FindControl("btnEliminar");
                    SetJavascriptForDeleteRecord(btnEliminarCtrl, resultado.Email);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridResultados_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "eliminar")
                {
                    //int resultadoId = Convert.ToInt32(this.GridResultados.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    //WebServiceHelper.EliminarResultadoDeAccionDeMarketing(accionDeMarketingCurrent.Id, resultadoId);
                    //var camp = accionDeMarketingCurrent.Resultados.Where(i => i.Id == resultadoId).Single();
                    //accionDeMarketingCurrent.Resultados.Remove(camp);
                    //Bind();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridAmbito_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    MaestroBase ambito = (MaestroBase)e.Row.DataItem;

                    ImageButton btnEditarCtrl = (ImageButton)e.Row.FindControl("btnEditar");
                    SetJavascriptForClientClickDirtyChech(btnEditarCtrl);

                    ImageButton btnEliminarCtrl = (ImageButton)e.Row.FindControl("btnEliminar");
                    SetJavascriptForDeleteRecord(btnEliminarCtrl, ambito.Nombre);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridAmbito_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "editar")
                {
                    int accionDeMarketingId = Convert.ToInt32(this.GridAmbito.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    this.Response.Redirect(string.Format(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlPuntoDeVentaEdit + "?Id={0}", accionDeMarketingId), true);
                }
                else if (e.CommandName == "eliminar")
                {
                    int accionDeMarketingId = Convert.ToInt32(this.GridAmbito.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    WebServiceHelper.EliminarPuntoDeVentaRelacionadoDeAccionDeMarketing(accionDeMarketingCurrent.Id, accionDeMarketingId);
                    var camp = accionDeMarketingCurrent.AmbitoList.Where(i => i.Id == accionDeMarketingId).Single();
                    accionDeMarketingCurrent.AmbitoList.Remove(camp);
                    Bind();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridAccionesDeMarketing_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    AccionDeMarketing accionDeMarketing = (AccionDeMarketing)e.Row.DataItem;

                    e.Row.Cells[0].Attributes.Add("title", "Editar");
                    e.Row.Cells[1].Attributes.Add("title", "Eliminar");

                    ImageButton btnEditarCtrl = (ImageButton)e.Row.FindControl("btnEditar");
                    SetJavascriptForClientClickDirtyChech(btnEditarCtrl);

                    ImageButton btnEliminarCtrl = (ImageButton)e.Row.FindControl("btnEliminar");
                    SetJavascriptForDeleteRecord(btnEliminarCtrl, accionDeMarketing.Nombre);

                    e.Row.Cells[6].Text = UIHelper.GetEnumDescription((DiscriminadorAccionDeMarketing)accionDeMarketing.Discriminador);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridAccionesDeMarketing_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "editar")
                {
                    int accionDeMarketingId = Convert.ToInt32(this.GridAccionesDeMarketing.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    this.Response.Redirect(string.Format(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlAccionDeMarketingSwap + "?Id={0}", accionDeMarketingId), true);
                }
                else if (e.CommandName == "eliminar")
                {
                    int accionDeMarketingId = Convert.ToInt32(this.GridAccionesDeMarketing.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    WebServiceHelper.EliminarAccionDeMarketingRelacionadaDeAccionDeMarketing(accionDeMarketingCurrent.Id, accionDeMarketingId);
                    var camp = accionDeMarketingCurrent.AccionesDeMarketingRelacionadasList.Where(i => i.Id == accionDeMarketingId).Single();
                    accionDeMarketingCurrent.AccionesDeMarketingRelacionadasList.Remove(camp);
                    Bind();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void lnkSaveButton_Click(object sender, EventArgs e)
        {
            try
            {
                SetData();
                Save();
                Bind();
                this.masterPage.ShowMessage(LocalizationProvider.Instance["Bo.Messages.MensajeSaveExitoso"], WebMessageType.Notification);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void volverButton_Click(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlPlanDeMarketingEdit + string.Format("?Id={0}", planDeMarketingCurrent.Id), true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void agregarListaDistribucionButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.accionDeMarketingCurrent.Id != 0)
                {
                    base.NavigationContext.AgregandoListasDeDistribucionAAccionDeMarketing = true;
                    base.NavigationContext.AccionDeMarketingId = this.accionDeMarketingCurrent.Id;
                    string cleanURL = this.Request.Url.AbsoluteUri.Replace(this.Request.Url.Query, string.Empty);
                    base.NavigationContext.UrlToGoBack = cleanURL;
                    Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlListaDeDistribucionList, true);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }


        private void agregarResultadosButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.accionDeMarketingCurrent.Id != 0)
                {
                    base.NavigationContext.AgregandoAccionesDeMarketingAAccionDeMarketing = true;
                    base.NavigationContext.AccionDeMarketingId = this.accionDeMarketingCurrent.Id;
                    string cleanURL = this.Request.Url.AbsoluteUri.Replace(this.Request.Url.Query, string.Empty);
                    base.NavigationContext.UrlToGoBack = cleanURL;
                    Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlAccionDeMarketingEmailResultadosEdit + string.Format("?accionDeMarketingId={0}", accionDeMarketingCurrent.Id), true);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }


        private void agregarAccionRelacionadaButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.accionDeMarketingCurrent.Id != 0)
                {
                    base.NavigationContext.AgregandoAccionesDeMarketingAAccionDeMarketing = true;
                    base.NavigationContext.AccionDeMarketingId = this.accionDeMarketingCurrent.Id;
                    string cleanURL = this.Request.Url.AbsoluteUri.Replace(this.Request.Url.Query, string.Empty);
                    base.NavigationContext.UrlToGoBack = cleanURL;
                    Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlAccionDeMarketingList + string.Format("?planDeMarketingId={0}&discriminadorId={1}", accionDeMarketingCurrent.PlanDeMarketingId, (int)DiscriminadorAccionDeMarketing.Comunicacion), true);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void lnkIrAPlan_Click(object sender, EventArgs e)
        {
            try
            {
                if (planDeMarketingCurrent != null)
                {
                    this.NavigationContext.RedirectTo(MiscClass.UrlPlanDeMarketingEdit, string.Format("?Id={0}", planDeMarketingCurrent.Id));
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void lnkReglaIrA_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.cboRegla.SelectedIndex >= 0)
                {                    
                    string reglaId = this.cboRegla.SelectedValue;
                    this.NavigationContext.RedirectTo(MiscClass.UrlReglaEdit, string.Format("?Id={0}", reglaId));
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
        

        private void agregarPuntoDeVentaButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.accionDeMarketingCurrent.Id != 0)
                {
                    base.NavigationContext.AgregandoPuntosDeVentaAAccionDeMarketing = true;
                    base.NavigationContext.AccionDeMarketingId = this.accionDeMarketingCurrent.Id;
                    string cleanURL = this.Request.Url.AbsoluteUri.Replace(this.Request.Url.Query, string.Empty);
                    base.NavigationContext.UrlToGoBack = cleanURL;
                    Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlPuntoDeVentaList, true);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkExportarAExcelListaDeDistribucion_Click(object sender, EventArgs e)
        {
            try
            {
                bool previousAllowPaging = this.GridListasDistribucion.AllowPaging;
                this.GridListasDistribucion.AllowPaging = false;

                BindGridListasDeDistribucion();

                GridViewExportExcelUtil.Export("ListasDeDistribucion.xls", this.GridListasDistribucion, 0, 1);

                this.GridListasDistribucion.AllowPaging = previousAllowPaging;
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkExportarAExcelResultados_Click(object sender, EventArgs e)
        {
            try
            {
                bool previousAllowPaging = this.GridResultados.AllowPaging;
                this.GridResultados.AllowPaging = false;

                BindGridResultados();

                GridViewExportExcelUtil.Export("Resultados.xls", this.GridResultados, 0);

                this.GridResultados.AllowPaging = previousAllowPaging;
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkExportarAExcelAmbitos_Click(object sender, EventArgs e)
        {
            try
            {
                bool previousAllowPaging = this.GridAmbito.AllowPaging;
                this.GridAmbito.AllowPaging = false;

                BindAmbitos();

                GridViewExportExcelUtil.Export("Ambitos.xls", this.GridAmbito, 0, 1, 3);

                this.GridAmbito.AllowPaging = previousAllowPaging;
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkExportarAExcelAccionesDeMkt_Click(object sender, EventArgs e)
        {
            try
            {
                bool previousAllowPaging = this.GridAccionesDeMarketing.AllowPaging;
                this.GridAccionesDeMarketing.AllowPaging = false;

                BindComunicaciones();

                GridViewExportExcelUtil.Export("ComunicacionesRelacionadas.xls", this.GridAccionesDeMarketing, 0, 1);

                this.GridAccionesDeMarketing.AllowPaging = previousAllowPaging;
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
    }
}